//
//  DCTakePhotoController.m
//  Demo
//
//  Created by zhaolin on 2023/1/10.
//

#import "DCTakePhotoController.h"
#import "DCRadiusTopView.h"
//#import "DCTakePhotoTool.h"
#import <AVFoundation/AVFoundation.h>

@interface DCTakePhotoController ()<DCNavgiteBarDelegate>

@property (nonatomic, strong) UIButton *takePhoto;
@property (nonatomic, strong) UIImageView *bgImage;
@property (nonatomic, strong) UIImageView *imageView;

//捕获设备，通常是前置摄像头，后置摄像头，麦克风（音频输入）
@property(nonatomic, strong)AVCaptureDevice *device;

//AVCaptureDeviceInput 代表输入设备，他使用AVCaptureDevice 来初始化
@property(nonatomic, strong)AVCaptureDeviceInput *input;

//当启动摄像头开始捕获输入
@property(nonatomic, strong)AVCaptureMetadataOutput *output;

@property (nonatomic, strong)AVCaptureStillImageOutput *ImageOutPut;

//session：由他把输入输出结合在一起，并开始启动捕获设备（摄像头）
@property(nonatomic, strong)AVCaptureSession *session;

//图像预览层，实时显示捕获的图像
@property(nonatomic, strong)AVCaptureVideoPreviewLayer *previewLayer;

@property (nonatomic, assign)BOOL isflashOn;
@property (nonatomic, strong)UIImage *image;

//@property (nonatomic, strong) DCTakePhotoTool *photoTool;

@end

@implementation DCTakePhotoController

- (void)viewDidLoad {
    [super viewDidLoad];
    BOOL canCa =  [self canUserCamear];
    if (canCa) {
        [self customCamera];
        [self configureUI];
    }
}

- (void)configureAlloc {
    [super configureAlloc];
    self.step = @"LIVENESS_INFO";

}

- (void)configureUI {
    self.fd_prefersNavigationBarHidden = YES;
    self.navgitBar = [[DCNavgiteBar alloc] initWithFrame:CGRectZero];
    self.navgitBar.delegate = self;
    self.navgitBar.hidden = NO;
    [self.view addSubview:self.navgitBar];
    [self.navgitBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_equalTo(0);
        make.height.mas_equalTo(88);
    }];
    
    [super updateNavrStyle:DCNavgiteBarStyleWhite];
    [self setTitleName:@"Live Photo"];

    self.navgitBar.backgroundColor = [UIColor clearColor];
    UIImageView *bgImage = [UIImageView new];
    _bgImage = bgImage;
    bgImage.image = [UIImage imageNamed:@"takePhotoBG"];
    [self.view addSubview:bgImage];
    [bgImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
    
    UILabel *tipsLabel = [UILabel new];
    tipsLabel.text = @"Please put your face in the frame and take a picture";
    tipsLabel.textColor = [UIColor colorWithString:@"#FFFFFF"];
    tipsLabel.font = DCFont_PF_Regular(13);
    tipsLabel.numberOfLines = 0;
    [bgImage addSubview:tipsLabel];
    [tipsLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(53);
        make.right.mas_equalTo(-53);
        make.top.mas_equalTo(self.navgitBar.mas_bottom).mas_equalTo(55);
    }];
        
    UIView *bottomView = [UIView new];
    bottomView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:bottomView];
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.height.mas_equalTo(168);
    }];
    
    DCRadiusTopView *radiusView = [[DCRadiusTopView alloc] init];
    [bottomView addSubview:radiusView];
    [radiusView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_equalTo(0);
        make.height.mas_equalTo(60);
    }];
    UIView *whiteView = [UIView new];
    whiteView.backgroundColor = [UIColor colorWithString:@"#FFFFFF"];
    [bottomView addSubview:whiteView];
    [whiteView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.height.mas_equalTo(108);
    }];
    
    UIButton *takePhoto = [UIButton buttonWithType:UIButtonTypeCustom];
    _takePhoto = takePhoto;
    [takePhoto setImage:[UIImage imageNamed:@"icon_take_photo_1"] forState:UIControlStateNormal];
    [takePhoto setImage:[UIImage imageNamed:@"icon_take_photo_2"] forState:UIControlStateSelected];
    [takePhoto addTarget:self action:@selector(takePhotoAction:) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:takePhoto];
    [takePhoto mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(bottomView);
        make.centerY.mas_equalTo(bottomView);
        make.width.height.mas_equalTo(96);
    }];
    
    [self.view bringSubviewToFront:self.navgitBar];
    [self.view bringSubviewToFront:bottomView];

}

- (void)takePhotoAction:(UIButton *)sender {
    if (!sender.isSelected) {
        [self shutterCamera];
    }else {
        [self cancle];
    }
    sender.selected = !sender.selected;
}

- (void)customCamera{
    //使用AVMediaTypeVideo 指明self.device代表视频，默认使用后置摄像头进行初始化
    self.device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    //使用设备初始化输入
    self.input = [[AVCaptureDeviceInput alloc]initWithDevice:self.device error:nil];
    //生成输出对象
    self.output = [[AVCaptureMetadataOutput alloc]init];
    self.ImageOutPut = [[AVCaptureStillImageOutput alloc] init];
    //生成会话，用来结合输入输出
    self.session = [[AVCaptureSession alloc]init];
    if ([self.session canSetSessionPreset:AVCaptureSessionPreset1280x720]) {
        self.session.sessionPreset = AVCaptureSessionPreset1280x720;
    }
    if ([self.session canAddInput:self.input]) {
        [self.session addInput:self.input];
    }
    
    if ([self.session canAddOutput:self.ImageOutPut]) {
        [self.session addOutput:self.ImageOutPut];
    }
    
    //使用self.session，初始化预览层，self.session负责驱动input进行信息的采集，layer负责把图像渲染显示
    self.previewLayer = [[AVCaptureVideoPreviewLayer alloc]initWithSession:self.session];
    self.previewLayer.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    [self.view.layer addSublayer:self.previewLayer];
    
    //开始启动
    [self.session startRunning];
    if ([_device lockForConfiguration:nil]) {
        if ([_device isFlashModeSupported:AVCaptureFlashModeAuto]) {
            [_device setFlashMode:AVCaptureFlashModeAuto];
        }
        //自动白平衡
        if ([_device isWhiteBalanceModeSupported:AVCaptureWhiteBalanceModeAutoWhiteBalance]) {
            [_device setWhiteBalanceMode:AVCaptureWhiteBalanceModeAutoWhiteBalance];
        }
        [_device unlockForConfiguration];
    }
}

#pragma mark - 截取照片
- (void) shutterCamera
{
    AVCaptureConnection * videoConnection = [self.ImageOutPut connectionWithMediaType:AVMediaTypeVideo];
    if (!videoConnection) {
        DLog(@"take photo failed!");
        return;
    }
    
    mWeakSelf
    [self.ImageOutPut captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
        if (imageDataSampleBuffer == NULL) {
            return;
        }
        NSData * imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
        weakSelf.image = [UIImage imageWithData:imageData];
        [weakSelf.session stopRunning];
//        [self saveImageToPhotoAlbum:self.image];
        weakSelf.imageView = [[UIImageView alloc]initWithFrame:weakSelf.previewLayer.frame];
        [weakSelf.view insertSubview:weakSelf.imageView belowSubview:weakSelf.bgImage];
        weakSelf.imageView.layer.masksToBounds = YES;
        weakSelf.imageView.image = weakSelf.image;
        DLog(@"image size = %@",NSStringFromCGSize(weakSelf.image.size));
//        [weakSelf uploadImage:imageData];
        if(weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(takePhotoComplete:)]) {
            [weakSelf.delegate takePhotoComplete:imageData];
        }
        dispatch_after(0.5, dispatch_get_main_queue() , ^{
            [self.navigationController popViewControllerAnimated:YES];
        });
    }];
}

-(void)cancle{
    [self.imageView removeFromSuperview];
    [self.session startRunning];
}

#pragma mark - 检查相机权限
- (BOOL)canUserCamear{
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusDenied) {
        [DCDCToast toastText:@"请打开相机权限 <设置-隐私-相机>"];
//        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"请打开相机权限" message:@"设置-隐私-相机" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
//        alertView.tag = 100;
//        [alertView show];
        return NO;
    }
    else{
        return YES;
    }
    return YES;
}
//- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
//    if (buttonIndex == 0 && alertView.tag == 100) {
//
//        NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
//
//        if([[UIApplication sharedApplication] canOpenURL:url]) {
//
//            [[UIApplication sharedApplication] openURL:url];
//
//        }
//    }
//}

- (void)uploadImage:(NSData *)imageData {
    [DCHttpRequest DCAuthUploadLiveImage:imageData CompleteBlock:^(NSURLSessionDataTask * _Nonnull operation, DCResponseData * _Nonnull responseObject) {
        if (responseObject.code == 200) {
            [self getNextStep];
        } else {
            [DCDCToast toastText:responseObject.message];
        }
    }];
}

- (void)getNextStep{
    [DCHttpRequest DCAuthNextStepCompleteBlock:^(NSURLSessionDataTask * _Nonnull operation, DCResponseData * _Nonnull responseObject) {
        if (responseObject.code == 200) {
            DLog(@"%@",responseObject.data);
        } else if(responseObject.code == 100){
            [DCDCToast toastText:@"认证完成"];
        }else {
            [DCDCToast toastText:responseObject.message];
        }
    }];
}
- (void)leftBackAction:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
@end
